package service

import (
	"fmt"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/teacher/service/dto"
	cDto "tuowei.com/common/dto"
)

type Order struct {
	service.Service
}

func (o Order) GetOrderList(orders *[]models.OfflineOrder, count *int64, req dto.GetOrderListRequest, teacherId int) error {
	orderTbName := models.OfflineOrder{}.TableName()
	stuTbName := models.SysStudent{}.TableName()
	db := o.Orm.Preload("Course").Preload("Customer").
		Scopes(
			cDto.Paginate(req.GetPageSize(), req.GetPageIndex())).
		Joins(fmt.Sprintf("inner join %[1]s on %[2]s.buyer_id = %[1]s.id", stuTbName, orderTbName)).
		Where("sys_offline_order.enrollment_teacher_id = ?", teacherId)
	if req.Status > 0 {
		db = db.Where(fmt.Sprintf("%s.status = ?", orderTbName), req.Status)
	}
	if req.CompletePay != nil {
		db = db.Where("complete_pay = ?", req.CompletePay)
	}
	return db.Order("id desc").Find(orders).Offset(-1).Limit(-1).Count(count).Error
}

func (o Order) Detail(id int, order *models.OfflineOrder) error {
	orderTbName := models.OfflineOrder{}.TableName()
	stuTbName := models.SysStudent{}.TableName()
	order.Id = id
	err := o.Orm.Preload("Course").Preload("Records").
		Preload("Customer.College").Preload("SubjectRelation").
		Joins(fmt.Sprintf("inner join %[1]s on %[2]s.buyer_id = %[1]s.id", stuTbName, orderTbName)).
		First(order).Error
	return err

}

type StatusCount struct {
	Status int `json:"status"`
	Total  int `json:"total"`
}

// 获取待跟进订单的数量
func (o Order) GetNums(status []int, teacherId int) []StatusCount {
	orderTbName := models.OfflineOrder{}.TableName()
	//stuTbName := models.SysStudent{}.TableName()
	m := make([]StatusCount, 0)
	o.Orm.Table(orderTbName).Where("enrollment_teacher_id = ?", teacherId).
		Where("sys_offline_order.status in (?)", status).
		//Joins(fmt.Sprintf("inner join %[1]s on %[2]s.buyer_id = %[1]s.id", stuTbName, orderTbName)).
		Select("sys_offline_order.status,count(*) as total").Group("sys_offline_order.status").
		Find(&m)
	return m
}

// StatisticsByTime 查询最近两个月的统计量
func (o Order) StatisticsByTime(year, month, teacherId int) (int, float64) {
	model := models.OfflineOrder{}
	var count int
	var total float64
	row := o.Orm.Table(model.TableName()).Where("enrollment_teacher_id = ?", teacherId).
		Where("year = ?", year).
		Where("month = ?", month).
		Where("complete_pay = 1").Where("status = ?", models.OfflineStatusComplete).
		Select("sum(price) as total,count(*) as count").Row()
	row.Scan(&total, &count)
	return count, total
}
